// 接口url 正式服必须为 https 协议接口
const BASE_URL = 'http://120.25.151.125:8080'


// 封装小程序内置接口请求
export function request(url, method, data, loadingText) {
  if (loadingText) wx.showLoading({
      title: loadingText, //提示的内容,
      mask: true, //是否显示透明蒙层
  })
  const ACTID = 'ygMall'
  const openid = wx.getStorageSync('openid')
  /*if(openid && !data.openid) {
      data.openid = openid.openid
  }*/
  return new Promise((reslove, reject) => {
      wx.request({
          url: BASE_URL + url, //开发者服务器接口地址",
          data: data, //请求的参数",
          method: method,
          header: {
              "Content-Type": "application/json"
          },
          success: res => {
              if (loadingText) wx.hideLoading()
                  // 开发环境才打印结果
              if (process.env.NODE_ENV == 'development') console.log(res.data)
                  // 响应错误
              if (res.statusCode != 200) {
                  wx.showToast({
                      title: '请稍后再试', //提示的内容,
                      image: '/static/icons/fail.png', //图标,
                  })
              }
              // else if (res.data && res.data.code != 200 && res.data.msg) {
              //     wx.showToast({
              //         title: res.data.msg, //提示的内容,
              //         image: '/static/icons/fail.png', //图标,
              //     })
              // }
              reslove(res.data)
          },
          fail: (err) => {
              // 网络异常
              if (loadingText) wx.hideLoading()
              wx.showToast({
                  title: '请稍后再试', //提示的内容,
                  image: '/static/icons/fail.png', //图标,
              })
              reject(err)
          },
          complete: () => {
              if (loadingText) wx.hideLoading()
          }
      })
  }).catch(err => {
      // 操作异常
      if (loadingText) wx.hideLoading()
      wx.showToast({
          title: '请稍后再试', //提示的内容,
          image: '/static/icons/fail.png', //图标,
      })
  })
}

// 封装get请求
export function get(url, data, loadingText) {
  return request(url, 'GET', data, loadingText)
}

// 封装post请求
export function post(url, data, loadingText) {
  return request(url, 'POST', data, loadingText)
}
// 跳转登录页
export function isAuth() {
  const openId = store.state.openId
  if (openId) return true
  else wx.navigateTo({ url: '/pages/auth/main' })
}







const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}
